const path = require('path');
const autoprefixer = require('autoprefixer');
const px2rem = require('postcss-plugin-px2rem');

const ROOT_PATH = path.resolve(__dirname);
const APP_PATH = path.resolve(ROOT_PATH, 'src');
const BUILD_PATH = path.resolve(ROOT_PATH, 'build');

// 导入package中的theme
const pkgPath = path.join(__dirname, 'package.json');
const pkg = require(pkgPath);

var theme = {};
if (pkg.theme && typeof(pkg.theme) === 'string') {
  var cfgPath = pkg.theme;
  if (cfgPath.charAt(0) === '.') {
    cfgPath = path.resolve(__dirname, cfgPath);
  }
  const getThemeConfig = require(cfgPath);
  theme = getThemeConfig();
} else if (pkg.theme && typeof(pkg.theme) === 'object') {
  theme = pkg.theme;
}

const svgSpriteDirs = [
  require.resolve('antd-mobile').replace(/warn\.js$/, ''), // antd-mobile 内置svg
  path.resolve(__dirname, 'images/svg'),  // 业务代码本地私有 svg 存放目录
];

module.exports = {
  entry: {
    bundle: path.resolve(APP_PATH, 'index.jsx'),
  },
  output: {
    path: BUILD_PATH,
    filename: 'bundle.js',
  },
  resolve: {
    root: path.resolve(__dirname),
    alias: {
      Component: path.resolve(APP_PATH, 'components'),
      Page: path.resolve(APP_PATH, 'components/Page'),
      Constants: path.resolve(APP_PATH, 'constants'),
      Utils: path.resolve(APP_PATH, 'utils'),
      Actions: path.resolve(APP_PATH, 'actions'),
      Style: path.resolve(APP_PATH, 'style'),
    },
    modulesDirectories: ['node_modules', path.join(__dirname, '../node_modules')],
    extensions: ['', '.web.js', '.js', '.jsx', '.json', '.svg'],
  },
  devServer: {
    historyApiFallback: true,
    disableHostCheck: true,
    hot: true,
    inline: true,
    progress: true,
  },
  postcss: [
    autoprefixer,
    px2rem({
      rootValue: 75,
      propBlackList: [
        'font-size',
        'border',
        'background-size',
      ],
      minPixelValue: 1,
    }),
  ],
  module: {
    loaders: [
      {
        test: /(\.js|\.jsx)$/,
        loaders: [
          'babel',
          'eslint-loader',
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        loaders: ['style', 'css', 'postcss'],
      },
      {
        test: /(\.less|\.module\.less)$/,
        loaders: [
          'style',
          'css',
          'postcss',
          `less-loader?{"sourceMap":true,"modifyVars":${JSON.stringify(theme)}}`
        ],
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'postcss', 'sass'],
        include: __dirname,
      },
      {
        // 字体文件之类的需要这个loader支持
        test: /\.(eot|woff|woff2|ttf)([?]?.*)$/,
        loader: 'file-loader',
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        loader: 'url',
        query: { limit: 10240 },
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(svg)$/i,
        loader: 'svg-sprite',
        include: svgSpriteDirs,
      },
    ],
  },
  devtool: 'source-map'
};
